<?php

namespace App\Http\Controllers\Client;

use App\Category;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use iscms\AlismsSdk\AlibabaAliqinFcSmsNumSendRequest;
use iscms\AlismsSdk\TopClient;
use Mews\Captcha\Facades\Captcha;
use App\Validate;
use App\Cdkey;
use App\Goods;
use App\Users;
use App\Address;
use App\Orders;
use App\Cart;
use App\Lable;
use App\Ad;
use Mail;
use Split;
use App\Rule;

class IndexController extends Controller
{
    //载入首页
    public function index() {
        $ad1 = Ad::where('id',1)->first();
//        $ad2 = Ad::where('id',2)->first();
        $ad3 = Ad::where('id',3)->first();
        $ad4 = Ad::where('id',7)->first();
//        $ad5 = Ad::where('id',8)->first();
        $ad6 = Ad::where('id',9)->first();
        $goods_1 = Goods::where('category_id',1)->take(6)->get();
//        dump($goods_1);
        $goods_2 = Goods::where('category_id',2)->take(6)->get();
//        dump($goods_2);
        $keyword1 = Category::where('id','1')->first();
        $keyword2 = Category::where('id','2')->first();
//        $cate = Category::all();
        $list = Orders::orderBy('create_time','desc')->take(10)->get();
        return view('client.index',['goods_1'=>$goods_1,'goods_2'=>$goods_2,'key1'=>$keyword1,'key2'=>$keyword2,'list'=>$list,'ad1'=>$ad1,'ad3'=>$ad3,'ad4'=>$ad4,'ad6'=>$ad6]);
    }

    //显示更多商品
    public function moreGoods($id) {
        $obj = new Goods;
        $ad4 = Ad::where('id',4)->first();
        $ad5 = Ad::where('id',5)->first();
        $ad6 = Ad::where('id',6)->first();
        $list = $obj->where('category_id',$id)->Paginate(9);
//        $list = Goods::all()->Paginate(9);
//        $t = Lable::where('id',$id)->first();
        return view('client.more',['list'=>$list,'ad4'=>$ad4,'ad5'=>$ad5,'ad6'=>$ad6]);
    }

    //商品详情载入
    public function goodsShow($id) {
        $ad4 = Ad::where('id',4)->first();
        $ad5 = Ad::where('id',5)->first();
        $ad6 = Ad::where('id',6)->first();
        $list = Goods::where('id',$id)->first();
        return view('client.type',['list'=>$list,'ad4'=>$ad4,'ad5'=>$ad5,'ad6'=>$ad6]);
    }

    //载入购物车
    public function showCart($id) {
        if(Session::get('uid')) {
            $list = Cart::where('user_id',$id)->get()->toArray();
            foreach ($list as $l => $value) {
                $g = Goods::where('id',$value['goods_id'])->first();

                $list[$l]['introduce'] = $g['goods_introduce'];
                $list[$l]['pic'] = $g['goods_picture'];
                $list[$l]['goods_inve'] = $g['goods_inventory'];
                //dump($list);
            }
            return view('client.toCart',['list'=>$list]);
        }
        else {
            $ad4 = Ad::where('id',4)->first();
            $ad5 = Ad::where('id',5)->first();
            $ad6 = Ad::where('id',6)->first();
            return view('client/login',['ad4'=>$ad4,'ad5'=>$ad5,'ad6'=>$ad6]);
        }
    }

    //加入购物车信息
    public function addCart()
    {
        $uid = Session::get('uid');
        if ($uid) {
//            dump(Session::get('uid'));
            $id = input::get('id');
//            dump($id);
            $dob = Cart::where('goods_id',$id)->where('user_id',$uid)->first();
            if(empty($dob)) {
                $num = input::get('number');
                //            dump($num);
                $goods = Goods::where('id', $id)->first();
                if ($num < $goods['goods_inventory']) {
                    $map = Cart::insert([
                        'goods_id' => $id,
                        'goods_name' => $goods['goods_name'],
                        'goods_price' => $goods['goods_price'],
                        'goods_num' => $num,
                        'user_id' => Session::get('uid'),
                    ]);
                    if ($map) {
                        return redirect()->back()->withErrors('添加成功!');
                    } else {
                        return redirect()->back()->withInput()->witErrors('添加失败!');
                    }
                } else {
                    return back()->withErrors('商品库存不足!');
                }
            }
            else {
                return back()->withErrors('购物车中已有该商品!');
            }
        } else {
            $ad4 = Ad::where('id',4)->first();
            $ad5 = Ad::where('id',5)->first();
            $ad6 = Ad::where('id',6)->first();
            return view('client/login',['ad4'=>$ad4,'ad5'=>$ad5,'ad6'=>$ad6])->withErrors('请登录!');

        }
    }
    //
    public function delCart($id) {
        $del = Cart::where('id',$id)->delete();
        if($del) {
            return back()->withErrors('删除成功!');
        }
        else {
            return redirect()->back()->withErrors('删除失败!');
        }
    }

    //载入订单信息（直接兑换）
    public function toOrder($id,$num) {
        $user = null;
        if(Session::get('uid')){
//            $address = Address::where('user_id',Session::get('uid'))->get()->toArray();
            $user = Users::where('id',Session::Get('uid'))->first();
            $list = Goods::where('id',$id)->first();
            $list['num'] = $num;
            return view('client.toOrder',['list'=>$list,'user'=>$user]);
        }
        else {
            $ad4 = Ad::where('id',4)->first();
            $ad5 = Ad::where('id',5)->first();
            $ad6 = Ad::where('id',6)->first();
            return view('client/login',['ad4'=>$ad4,'ad5'=>$ad5,'ad6'=>$ad6])->withErrors('请先登录!');
        }
    }

    //购物车订单确认
    public function toOrders() {
        $user = null;
        $id = input::get('check_cart');
        $num = input::get('number');
        $total_price = input::get('total_price');
        if(!empty($id)) {
            foreach ($id as $i) {
                $t = $num[$i];
                $list = Cart::where('id', $i)->update(['goods_num' => $t]);
            }
            $newCart = Cart::whereIn('id', $id)->get()->toArray();

            foreach ($newCart as $a=>$value) {
                $goods = Goods::where('id',$value['goods_id'])->first();
                $newCart[$a]['pic'] = $goods['goods_picture'];
                $newCart[$a]['intr'] = $goods['goods_introduce'];
            }
            if ($newCart) {
                $user = Users::where('id',Session::get('uid'))->first();
                return view('client.toOrders', ['newCart' => $newCart,'user'=>$user,'total_price'=>$total_price]);
            } else {
                return redirect()->back()->withErrors('提交失败!');
            }
        }
        else {
            return back()->withErrors('请选择商品!');
        }
    }

    //提交订单
    public function order()
    {

        $text = input::get('text');
        $id = input::get('cid');
        $way = input::get('way');
        $address = input::get('address');
        $g_id = input::get('id');
        $g_num = input::get('num');
        $total_price = input::get('total_price');
        $uid = Session::get('uid');
        $code = input::get('code');
        $phone = Session::get('phone');
        //添加新地址
        $address = input::get('address');

        $v = Cdkey::where('phone', $phone)->first();
//
        $user = Users::where('id', $uid)->first();
//        exit();
        if ($way == 2) {
                if ($v && time() - strtotime($v['update_time']) < 300 && $code == $v['code']) {
                    //生成订单编号
                    $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
                    $o_id = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
                    //        dump($o_id);

                    $data['integral'] = (int)($user['integral']) - (int)($total_price);
                    if ($data['integral'] >= 0) {
                        //            dump($id);
                        foreach ($id as $i => $value) {
                            //                dump($value);
                            $map = Orders::insert([
                                'order_id' => $o_id,
                                'goods_id' => $g_id[$value],
                                'goods_num' => $g_num[$value],
                                'total_price' => $total_price,
                                'user_id' => $uid,
                                'get_way' => $way,
//                                'address' => $address,
                                'code' => $v['code'],
                                'status' => 0,
                            ]);
                        }
//                        $update = Users::where('id', $uid)->update($data);
                        if ($map) {
//                            $number = Goods::whereIn('id', $g_id)->decrement('goods_inventory');
//                            if ($id) {
                                $del = Cart::whereIn('id', $id)->delete();
                            $addr = Users::where('id',$uid)->update(['address'=>$address]);
//                            }
                            return view('client.success', ['o_id' => $o_id, 'total_price' => $total_price, 'get_way' => $way]);
                        } else {
                            return Redirect::to('client/showCart/'.$uid)->withErrors('兑换失败!');
                        }
                    } else {
                        return Redirect::to('client/showCart/'.$uid)->withErrors('积分不足!');
                    }
                } else {
                    return Redirect::to('client/showCart/'.$uid)->withErrors('验证码错误或超时!');
                }
        }
        else {
//            dump($v['update_time']);
//            $t = time();
//            dump($t);
//            $s = time() - strtotime($v['update_time']);
//            $x = time() - strtotime($v['update_time']) < 300 ;
//            dump(strtotime($v['update_time']));
//            dump($s);
//            dump($x);
//            exit();
                $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
                $o_id = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
                //创建随机数
                $num = rand(100000, 999999); //组装参数
                //        dump($o_id);
                $user = Users::where('id', $uid)->first();
                $data['integral'] = (int)($user['integral']) - (int)($total_price);

                if ($data['integral'] > 0) {
                    //            dump($id);
                    foreach ($id as $i => $value) {
                        //                dump($value);
                        $map = Orders::insert([
                            'order_id' => $o_id,
                            'goods_id' => $g_id[$value],
                            'goods_num' => $g_num[$value],
                            'total_price' => $total_price,
                            'user_id' => $uid,
                            'get_way' => $way,
                            'address' => $address,
                            'code' => $num,
                            'status' => 0,
                        ]);
                    }
                    //$update = Users::where('id', $uid)->update($data);
                    if ($map ) {
                       // $number = Goods::whereIn('id', $g_id)->decrement('goods_inventory');
                        if ($id) {
                            $del = Cart::whereIn('id', $id)->delete();
                        }
                        $c = new TopClient();
//                        //创建随机数
//                        $num = rand(100000, 999999); //组装参数
                        //生成json串
                        $p = [
                            'number' => "$num",
                        ];
                        $pp = json_encode($p);
                        //获取密钥
                        $c->appkey = config('alisms.KEY');
                        $c->secretKey = config('alisms.SECRETKEY');
                        //设置参数
                        $req = new AlibabaAliqinFcSmsNumSendRequest();
                        $req->setSmsType('normal');
                        $req->setSmsParam($pp);
                        $req->setSmsFreeSignName('保祥云商城');
                        $req->setRecNum($phone);
                        $req->setSmsTemplateCode('SMS_35940155');
                        $rsp = $c->execute($req);
                        $vali = Cdkey::where('phone', $phone)->first();
                        if ($vali) {
                            Cdkey::where('phone', $phone)->update(['code' => $num]);
                        } else {
                            Cdkey::insert([
                                'code' => $num,
                                'phone' => $phone
                            ]);
                        }
                        $rsp = json_encode($rsp, JSON_UNESCAPED_UNICODE);
                        return view('client.success', ['o_id' => $o_id, 'total_price' => $total_price, 'get_way' => $way])->withErrors('兑换成功!');
                    } else {
                        return redirect()->back()->withErrors('兑换失败!');
                    }
                } else {
                    return redirect()->back()->withErrors('积分不足!');
                }

        }
    }

    //生成手机兑换码
    public function convertPhone()
    {
        $phone = Session::get('phone');
        $c = new TopClient();
        //创建随机数
        $num = rand(100000, 999999); //组装参数
        //生成json串
        $p = [
            'number' => "$num",
        ];
        $pp = json_encode($p);
        //获取密钥
        $c->appkey = config('alisms.KEY');
        $c->secretKey = config('alisms.SECRETKEY');
        //设置参数
        $req = new AlibabaAliqinFcSmsNumSendRequest();
        $req->setSmsType('normal');
        $req->setSmsParam($pp);
        $req->setSmsFreeSignName('保祥云商城');
        $req->setRecNum($phone);
        $req->setSmsTemplateCode('SMS_35940155');
        $rsp = $c->execute($req);
        $vali = Cdkey::where('phone', $phone)->first();
        if ($vali) {
            Cdkey::where('phone', $phone)->update(['code' => $num]);
        } else {
            Cdkey::insert([
                'code' => $num,
                'phone' => $phone
            ]);
        }
        echo $rsp = json_encode($rsp, JSON_UNESCAPED_UNICODE);
    }


    //批量商品订单
//    public function orders() {
//        //return (23213);
//        $g_id = input::get('gid');
//        $g_num = input::get('num');
//        $total_price = input::get('total_price');
//        $uid = Session::get('uid');
//        $way = input::get('way');
//        $address = input::get('addre');
//        $gid=implode(',',$g_id);
//        $gnum=implode(',',$g_num);
//        dump($gid);
//        dump($gnum);
//        dump($total_price);
//        dump($uid);
//        dump($way);
//        dump($address);
//        //生成订单编号
//        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
//        $o_id = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
//
//        $user = Users::where('id',$uid)->first()->toArray();
//        $data['integral'] = (int)($user['integral']) - (int)($total_price);
//        if($data['integral'] > 0 ) {
//            $map = Orders::insert([
//                'order_id' => $o_id,
//                'goods_id' => $gid,
//                'goods_num' => $gnum,
//                'total_price' => $total_price,
//                'user_id' => $uid,
//                'get_way' => $way,
//                'address' => $address,
//                'status' => 0,
//            ]);
//            $update = Users::where('id',$uid)->update($data);
//            if($map && $update) {
//                $number = Goods::where('id',$gid)->decrement('goods_inventory');
//                return Redirect::to('')->withErrors('兑换成功!');
//            }
//            else {
//                return redirect()->back()->withErrors('兑换失败!');
//            }
//        }
//        else {
//            return redirect()->back()->withInput()->withErrors('积分不足!');
//        }
//    }

    //载入会员中心
    public function user() {
        $uid = Session::get('uid');
        if(empty($uid)) {
            return view('client.jump');
        }
        //获取个人信息
        $data = Users::where('id',$uid)->first()->toArray();
//        $address = Address::where('user_id',$uid)->get()->toArray();

        if($data) {
            return view('client.user',['data'=>$data]);
        }
        else {
            return redirect()->back()->withErrors('获取失败信息!');
        }
    }

    //更新个人信息
    public function updateUser() {
        $obj = new Users();
//        $validate = $obj->userValidate(Input::all());
//        if($validate->fails()) {
//            $warnings = $validate->messages();
//            $show_warning = $warnings->first();
//            return redirect()->back()->with('show_warning',$show_warning);
//        }
        $id = input::get('id');
        $uid = Session::get('uid');
        $data['username'] = input::get('username');
        $data['name'] = input::get('name');
        $data['phone'] = input::get('phone');
        $data['email'] = input::get('email');
        $data['sex'] = input::get('sex');
        $data['birth'] = input::get('birth');
        $data['car_num'] = input::get('car_num');
        $data['user_num'] = input::get('user_num');
        $data['address'] = input::get('address');
//        dump($data);
        $map = $obj->where('id',$id)->update($data);
        if($map) {
            Session::put('name',$data['name']);
            return redirect()->back()->with('修改成功!');
        }
        else {
            return redirect()->back()->withErrors('修改失败!');
        }
    }

    //修改密码
    public function changePass() {
        $uid = Session::get('uid');
        $password1 = md5(input::get('password1'));
        $password2 = md5(input::get('password2'));
        $password3 = md5(input::get('password3'));

        if($password2 != $password3) {
            return back()->withErrors('两次新密码输入不一致!');
        }
        $user = Users::where('id',$uid)->first();
        if($password1 != $user['password']) {
            return back()->withErrors('当前密码输入错误!');
        }
        $list = Users::where('id',$uid)->update(['password'=>$password2]);
        if($list) {
            return back()->withErrors('修改成功!');
        }
        else {
            return back()->withErrors('修改失败!');
        }
    }

    //添加新地址
    public function toAddress() {

        $get_addre = input::get('get_addre');
        $uid = Session::get('uid');
        if(empty($get_addre)) {
            return redirect()->back()->withInput()->withErrors('缺少参数!');
        }
        $list = Users::insert([
            'get_address' => $get_addre,
        ]);
        if($list) {
            return Redirect::to('client/user')->withErrors('添加成功!');
        }
        else {
            return redirect()->bakc()->withErrors('添加是吧!');
        }
    }

    //修改地址
    public function updateAddress() {
        $data['address'] = input::get('address');
        if(empty($data['address'])) {
            return redirect()->back()->withInput()->withErrors('缺少参数!');
        }
        $map = Users::where('id',Session::get('uid'))->update($data);
        if($map) {
            return Redirect::to('client/user')->withErrors('修改成功!');
        }
        else {
            return redirect()->back()->withInput()->withErrors('修改失败!');
        }
    }

    //更新头像
    public function updateAvatar() {
        $uid = Session::get('uid');
        $avatar = input::file('avatar');
        if(!empty($avatar)) {
            if($avatar->isValid()) {
                $allowed_extensions = ['png','jpg','gif'];
                if($avatar->getClientOriginalExtension() && !in_array($avatar->getClientOriginalExtension(),$allowed_extensions)) {
                    return ['error' => 'You may only upload png, jpg or gif.'];
                }
                $destinationPath = 'productImg/'.date('Y-m-d');
                $extension = $avatar->getClientOriginalExtension();
                $avatarName = str_random(10). '.' . $extension;
                $avatar->move($destinationPath,$avatarName);
                $avatarPath = asset($destinationPath.$avatarName);
                $data['avatar'] = date('Y-m-d'). '/' . $avatarName;
                $list = Users::where('id',$uid)->update($data);
                if($list) {
                    return Redirect::to('client/user')->withErrors('更新成功!');
                }
                else {
                    return redirect()->back()->withInput()->withErrors('更新失败!');
                }
            }
            else {
                return redirect()->back()->withInput()->withErrors('文件上传失败!');
            }
        }
    }

    //兑换列表
    public function query() {
        $uid = Session::get('uid');
        if($uid) {
            $order = Orders::where('user_id',$uid)->orderBy('order_id','desc')->paginate(10);
            foreach ($order as $ord => $value) {
                $list = Goods::where('id',$value['goods_id'])->first()->toArray();
                $order[$ord]['pic'] = $list['goods_picture'];
                $order[$ord]['intr'] = $list['goods_introduce'];
                $order[$ord]['name'] = $list['goods_name'];
                $order[$ord]['price'] = $list['goods_price'];
            }
            return view('client/findOrder',['order'=>$order]);
        }
        else {
            $ad4 = Ad::where('id',4)->first();
            $ad5 = Ad::where('id',5)->first();
            $ad6 = Ad::where('id',6)->first();
            return view('client.login',['ad4'=>$ad4,'ad5'=>$ad5,'ad6'=>$ad6]);
        }
    }


    //兑换查询
    public function search() {
        $search = input::get('search');
        $list = Goods::where('goods_name','like',"%$search%")->first();
        $order = Orders::where('order_id', 'like', "%$search%")->orWhere('goods_id', $list['id'])->orderBy('order_id', 'desc')->paginate(10);
        if($order) {
            foreach ($order as $ord => $value) {
                $list = Goods::where('id', $value['goods_id'])->first()->toArray();
                $order[$ord]['pic'] = $list['goods_picture'];
                $order[$ord]['intr'] = $list['goods_introduce'];
                $order[$ord]['name'] = $list['goods_name'];
                $order[$ord]['price'] = $list['goods_price'];
            }

            return view('client/findOrder', ['order' => $order]);
        }
        else {
            return redirect()->back()->withInput()->withErrors('条件不存在!');
        }
    }

     //删除兑换订单
    public function delOrder($id) {
        $del = Orders::where('id',$id)->delete();
        return back()->withErrors('订单已删除');
    }

    //兑换规则
    public function rule() {
        $rule = Rule::where('id',1)->first();
        return view('client.rule',compact('rule'));
    }
}
